<?php
//会话校验函数
function sVerify(){
    $session_uid = cookie('uid');
    if ($session_uid==NULL) {
        $auth = cookie('auth'); //读取"记住我"cookie
        if ($auth==NULL) {
            cookie('uid', NULL);
            return NULL;
        }
        Log::write('auth:'.$auth, Log::ERR);
        $now = time();
        list($email, $identifier, $token) = explode(':', $auth);
        if (!($email && ctype_alnum($identifier) && ctype_alnum($token))) {
            cookie('uid', NULL);
            return NULL;
        }
        $arr = M('user')->where(array('email' => array('eq', $email)))->find();
        if ($arr) {
            $lidentifier = md5(G_SALT . md5($email . G_SALT));
            if ($token != $arr['token'] || $now > $arr['timeout'] || $identifier != $lidentifier) {
                cookie('uid', NULL);
                return NULL;
            }
            //刷新登陆时间和IP
            $arr['lastime'] = time();
            $arr['lastip'] = get_client_ip();
            M('user')->save($arr);
            
            $session_uid = $arr['id'];
        }
    }
    else {
        $resU = M('user')->where('id='.$session_uid)->find();
        if ($resU['identifer']!='logined') {
            cookie('uid', NULL);
            return NULL;
        }
    }
    
    return $session_uid;
}
//实时发送邮件
function think_send_mail($to, $name, $subject = '', $body = '', $attachment = null) {
    error_reporting(E_ALL);
    $config = C('THINK_EMAIL');
    Vendor('PHPMailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件
    Vendor('PHPMailer.class#smtp'); //从PHPMailer目录导class.smtp.php类文件
    $mail = new PHPMailer(); //PHPMailer对象
    $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();  // 设定使用SMTP服务
    $mail->SMTPDebug = 1;
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth = true;                  // 启用 SMTP 验证功能
    $mail->SMTPSecure = $config['PROTOCOL'];                 // 使用安全协议
    $mail->Host = $config['SMTP_HOST'];  // SMTP 服务器
    $mail->Port = $config['SMTP_PORT'];  // SMTP服务器的端口号
    $mail->Username = $config['SMTP_USER'];  // SMTP服务器用户名
    $mail->Password = $config['SMTP_PASS'];  // SMTP服务器密码
    $mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
    $replyEmail = $config['REPLY_EMAIL'] ? $config['REPLY_EMAIL'] : $config['FROM_EMAIL'];
    $replyName = $config['REPLY_NAME'] ? $config['REPLY_NAME'] : $config['FROM_NAME'];
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->AltBody = "为了查看该邮件，请切换到支持 HTML 的邮件客户端";
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $name);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    try{
        $ret = $mail->Send();
        if (!$ret) {
            Log::write('[SendMail]'.$mail->ErrorInfo);
        }
        return $ret;
    }
    catch(Exception $e){
        Log::write('[SendMail]'.$mail->ErrorInfo.',[Exception]'.$e->getMessage());
        return false;
    }
}
//发送邮箱账号激活邮件
function signupEV($name, $uid, $now=false) {
    $ret = false;
    $now = time();
    $user = M('user')->where('id='.$uid)->find();
    //先删除旧token
    M('emailverify')->where('uid='.$uid)->delete();

    $token = md5($user['email'].$now);
    $verifyData = array(
        'token' => $token,
        'uid' => $uid,
        'ctime' => $now,
    );
    $ret = M('emailverify')->add($verifyData);
    $url = "http://www.".getDomain()."/Index/Login/emailverify/code/1/token/$token";
    $to = $user['email'];
    $subject = "欢迎您加入般若虾——中高端脑力兼职";
    $body = "亲爱的$name:<br/>&nbsp;&nbsp;&nbsp;&nbsp;感谢您注册般若虾，般若虾专注中高端脑力兼职，是中高端人才的聚集地，中小、初创企业的项目园。<br/>&nbsp;&nbsp;&nbsp;&nbsp;请点击如下链接完成邮箱验证，激活账户:<br/>&nbsp;&nbsp;&nbsp;&nbsp;<a href='".$url."'>$url</a><br/>";
    $body = mailPostfix($body);
    if ($now) {
        $ret = think_send_mail($to, $name, $subject, $body);
    }
    else {
        $ret = mailqueue_push($to, $name, $subject, $body);
    }
    return $ret;
}

//推入数据库邮件队列
//参数说明: $name 接收者名称
function mailqueue_push($to, $name, $subject, $body) {
    $data = array(
        'receiver' => $to,
        'name' => $name,
        'subject' => $subject,
        'body' => $body,
        'uptime' => time(),
    );
    return $resMailq = M('mailqueue')->add($data);
}

//时间格式
function timespan($timestamp, $current_time = 0) {
    if (!$current_time)
        $current_time = time();
    $span = $current_time - $timestamp;
    if ($span < 60) {
        return $span . "秒前";
    } else if ($span < 3600) {
        return intval($span / 60) . "分钟前";
    } else if ($span < 24 * 3600) {
        return intval($span / 3600) . "小时前";
    } else {
        return intval($span / (24 * 3600)) . "天前";
    }
}

//显示Photo
function toPhoto($uid = 0) {
    $str = M('user_info')->where('uid=' . $uid)->getField('photo');
    if ($str == '') {
        $str = 'Public/themes/images/fimg.png';
    }
    return $str;
}

//显示昵称
function toXingming($uid = 0) {
    $str = M('user_info')->where('uid=' . $uid)->getField('nickname');
    if ($str == '') {
        $str = '未填写';
    }
    return $str;
}

//根据id查询字典表名称
function toName($id = 0) {
    $str = M('dic')->where('id=' . $id)->getField('name');
    return $str;
}

//显示性别
function toGender($gender){
    $str = '未填写';
    if ($gender==1) {
        $str = '男';
    }
    else if ($gender==2) {
        $str = '女';
    }
    return $str;
}
//时间戳转可读
function toTime($time, $fat = 'Y-m-d H:i:s'){
    $str = '暂无';
    if ($time>0) {
        $str = date($fat, $time);
    }
    return $str;
}

//datetime类型转字符串
function datetimeToStr($format, $date) {
    if (!$date || $date==0) {
        return "未填写";
    }
    $time = strtotime($date);
    return date($format, $time);
}

//隐藏电话号码中间四位
function hidetel($phone){
    $IsWhat = preg_match('/(0[0-9]{2,3}[-]?[2-9][0-9]{6,7}[-]?[0-9]?)/i',$phone); //固定电话
    if($IsWhat == 1){
        return preg_replace('/(0[0-9]{2,3}[-]?[2-9])[0-9]{3,4}([0-9]{3}[-]?[0-9]?)/i','$1****$2',$phone);
    }else{
        return  preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
    }
}

    //隐藏电子邮箱地址@之前中间几位
function hidemail($email){
    if (strlen($email)<=0) {
        return '';
    }
    $arr = explode('@', $email);
    $idlen = strlen($arr[0]);
    $id = $arr[0];
    $newid = '';
    if($idlen==2){
        $newid = preg_replace('/(\w)\w/i', '$1*', $id);
    }
    elseif($idlen==3){
        $newid = preg_replace('/(\w{2})\w/i', '$1*', $id);
    }
    elseif($idlen==4){
        $newid = preg_replace('/(\w{2})\w(\w)/i', '$1*$2', $id);
    }
    elseif($idlen==5){
        $newid = preg_replace('/(\w{2})\w{2}(\w)/i', '$1**$2', $id);
    }
    elseif($idlen>=6){
        $newid = preg_replace('/(\w{2})\w{2,}(\w{2})/i', '$1**$2', $id);
    }
    return $newid.'@'.$arr[1];
}

//增减团队职位数,若是减,则$jobs、$jobsok为负数
function setTeamJobNum($teamid, $jobs, $jobsok){
    //取当前数量
    $teamTab = M('team');
    $resTeam = $teamTab->where('id='.$teamid)->find();
    if (!$resTeam) {
        return false;
    }
    $resTeam['jobs'] = $resTeam['jobs'] + $jobs;
    $resTeam['jobsok'] = $resTeam['jobsok'] + $jobsok;
    if ($resTeam['jobs']<0 || $resTeam['jobsok']<0 || $resTeam['jobs']<$resTeam['jobsok']){
        return false;
    }
    $ret = $teamTab->save($resTeam);
    return $ret;
}

//向站内用户发送通知
function sendNotice($uid, $content) {
    $data = array(
        'uid'=>$uid,
        'content'=>$content,
        'ctime'=>time(),
    );
    $ret = M('office_log')->add($data);
    return $ret;
}

//向团队创建者、项目创建者、部门经理发通知
/*参数:$uid,通知发送者uid
 *     $teamid,发送者所在团队ID
 *     $pid,发送者所在项目ID
 *     $content,通知内容
 *     $tc,bool,是否给团队创建者发
 *     $pc,bool,是否给项目创建者发
 *     $dm,bool,是否给部门经理发
 */
function sendNoticeBatch($uid, $teamid, $pid, $content, $tc=true, $pc=true, $dm=true) {
    $data = array();
    $now = time();
    $resTeam = false;
    $resPrj = false;
    if ($tc) {
        $resTeam = M('team')->where('id='.$teamid)->find();
        if($resTeam){
            $data[] = array(
                'uid'=>$resTeam['uid'],
                'content'=>$content,
                'ctime'=>$now,
            );
        }
    }
    if ($pc) {
        $resPrj = M('project')->where('id='.$pid)->find();
        if ($resPrj) {
            if (($resTeam && $resPrj['uid']!=$resTeam['uid']) || !$resTeam) {
                $data[] = array(
                    'uid'=>$resPrj['uid'],
                    'content'=>$content,
                    'ctime'=>$now,
                );
            }
        }
    }
    /*
    if ($dm) {
        $resJobuser = M('job_user')->where('uid='.$uid.' and state=2')->find();
        if ($resJobuser) {
            $resCard = M('taskcard')->where('id='.$resJobuser['did'].' and state>0')->find();
            if ($resCard) {
                $data[] = array(
                    'uid'=>$resCard['uid'],
                    'content'=>$content,
                    'ctime'=>$now,
                );
            }
        }
    }
     */
    Log::write('[sendNoticeBatch]'.json_encode($data), Log::INFO);
    $ret = M('office_log')->addAll($data);
    return $ret;
}

/**
  +----------------------------------------------------------
 * 生成随机字符串
  +----------------------------------------------------------
 * @param int       $length  要生成的随机字符串长度
 * @param string    $type    随机码类型：0，数字+大小写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
  +----------------------------------------------------------
 * @return string
  +----------------------------------------------------------
 */
function randCode($length = 5, $type = 0) {
    $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
    if ($type == 0) {
        array_pop($arr);
        $string = implode("", $arr);
    } elseif ($type == "-1") {
        $string = implode("", $arr);
    } else {
        $string = $arr[$type];
    }
    $count = strlen($string) - 1;
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $string[rand(0, $count)];
    }
    return $code;
}

//组装邮件html正文
function composeMailHtml($chenhu, $body) {
    $content =<<<STR
        <div>$chenhu,<br/>
        $body<br/>
        <p>般若虾团队</p>
        </div>
STR;
    return $content;
}

//薪酬类型转文字
function toSalaryDesc($st) {
    $str = '自行商议';
    if ($st==1) {
        $str = '月薪';
    }
    else if ($str==2) {
        $str = '按项目结算';
    }
    return $str;
}

//是否托管资金描述
function toTuoguanDesc($t,$isp=false,$p=0) {
    //Log::write('[toTuoguanDesc]$t:'.$t.',isp:'.$isp.',p:'.$p, Log::ERR);
    $str = "未知";
    if ($isp) {
        if ($p==2) {
            return '已发放';
        }
    }
    if ($t==0) {
        $str = "未托管";
    }
    else if ($t==1) {
        $str = "已托管";
    }
    else if ($t==2) {
        $str = "已结算";
    }
    else if ($t==4) {
        $str = "部分托管";
    }else if ($t==5) {
        $str = "部分结算";
    }
    return $str;
}

//通用邮件内容拼装
function composeMail($name, $content) {
    return "亲爱的$name,<br/>&nbsp;&nbsp;&nbsp;&nbsp;$content<br/>般若虾团队<br/>".date('Y.m.d',time());
}
//系统邮件后缀
function mailPostfix($content){
    return $content."<p style='color:#3f3f3f;font-size:13px;'>&nbsp;&nbsp;&nbsp;&nbsp;<a href='"."http://".$_SERVER['HTTP_HOST']."'>般若虾</a>|欢迎关注<a href='http://weibo.com/u/5341115354'>般若虾官方微博</a>并和我们互动!</p><p style='color:#afafaf;font-size:13px;'>&nbsp;&nbsp;&nbsp;&nbsp;本邮件为系统自动发出，请勿回复。</p>";
}
//运营团队邮件后缀
function mailTeampost($content) {
    return $content."<br/><br/>般若虾运营团队<br/>".  date('Y.m.d');
}

//作品描述
function toWorkDesc($desc){
    if ($desc=='') {
        return '用户未添加描述';
    }
    return $desc;
}

function create_image($uploadedfile, $savefilename, $x, $y, $w, $h)
{
    if (empty($uploadedfile)) {
        return false;
    }
    $targ_w = $targ_h = 300;
    $jpeg_quality = 100;

    if (!$info = getimagesize($uploadedfile))
        return false;

    switch ($info['mime']) {
        case 'image/jpeg':
            $img_r = imagecreatefromjpeg($uploadedfile);
            break;
        case 'image/gif':
            $img_r = imagecreatefromgif($uploadedfile);
            break;
        case 'image/png':
            $img_r = imagecreatefrompng($uploadedfile);
            break;
        default:
            return false;
    }
    $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
    //分配颜色
    $alpha = imagecolorallocatealpha($dst_r, 0, 0, 0, 127);
    imagefill($dst_r, 0, 0, $alpha);
    
    imagecopyresampled($dst_r, $img_r, 0, 0, $x, $y, $targ_w, $targ_h, $w, $h);
    imagesavealpha($dst_r, true); 

    $dir = dirname($savefilename);
    if (file_exists($dir) && is_dir($dir)) { //如果存在这个文件并且这个文件是个目录就不动作
        Log::write('[cutImg]目录' . $dir . '已存在');
    } else {
        Log::write('[cutImg]创建目录' . $dir);
        mkdir($dir, 0777, true); //否则就创造这个目录
    }


    switch ($info['mime']) {
        case 'image/jpeg':
            imagejpeg($dst_r, $savefilename, $jpeg_quality); //100 is the quality settings, values range from 0-100.
            break;
        case 'image/gif':
            imagegif($dst_r, $savefilename, $jpeg_quality); //100 is the quality settings, values range from 0-100.
            break;
        case 'image/png':
            imagepng($dst_r, $savefilename); //100 is the quality settings, values range from 0-100.
            break;
    }

    imagedestroy($img_r);
    imagedestroy($dst_r);

    return true;
}

    //ajax失败返回
    function ajaxf($msg='', $data=null) {
        echo json_encode(array('success'=>0, 'msg'=>$msg, 'data'=>$data));
        exit;
    }
    
    //ajax成功返回
    function ajaxs($code=1,$msg='',$data=null) {
        echo json_encode(array('success'=>$code, 'msg'=>$msg, 'data'=>$data));
        exit;
    }
    
    //字符串内容缩略
    function summary($str, $num){
        if (mb_strlen($str)>$num) {
            return mb_substr($str, 0, $num, 'utf-8').'...';
        }
        else{
            return $str;
        }
    }

    //头像url
    function toTalentPhoto($url, $ut){
        if (empty($url)) {
            if ($ut==1) {
                return 'Public/themes/images/img-people.png';
            }
            else if ($ut==2) {
                return 'Public/themes/images/LOGO-gray.png';
            }
        }
        return $url;
    }
    
    //logo url
    function toLogo($url){
        if (empty($url)) {
            return 'Public/themes/images/LOGO-gray.png';
        }
        return $url;
    }
    
    //隐私设置
    function toPriFlag($flag) {
        $strArr = array(1=>'仅自己可见',2=>'队友及雇主可见',3=>'所有人可见');
        if ($flag>=1 && $flag<=3) {
            return $strArr[$flag];
        }
        else {
            return '队友及雇主可见';
        }
    }
    
    //隐私信息过滤
    function userInfoFilter(&$myInfoArr, &$otherInfoArr) {
        if ($myInfoArr['uid']==$otherInfoArr['uid']) {
            return NULL;
        }
        $g_uif_keys = array('f_realname'=>'realname','f_gender'=>'gender','f_birthday'=>'birthday','f_blog'=>'blog','f_weibo'=>'weibo','f_school'=>'school','f_about'=>'about','f_jineng'=>'jineng','f_jianli'=>'jianli','f_works'=>'works');
        //判断浏览者与被浏览者关系
        $r = 1;//两者关系，1为陌生人，2为队友或浏览者是雇主
        //浏览者是否雇主
        if ($myInfoArr['utype']==2) {
            $r = 2;
        }
        if ($myInfoArr['teamid']!=-1 && $myInfoArr['teamid']==$otherInfoArr['teamid']) {
            $r = 2;
        }
        $resPrj = M('project')->where('id='.$myInfoArr['projectid'])->find();
        $resJu = M('job')->where("pid='".$myInfoArr['projectid']."' and moneyin=1")->select();
        if ($resPrj['uid']==$myInfoArr['uid'] && $resJu) {//有已托管职位，是雇主
            $r = 2;
        }
        
        //过滤字段
        $resPri = M('privacyflag')->where("uid='".$otherInfoArr['uid']."'")->find();
        //Log::write('otherInfoArr:'.  json_encode($otherInfoArr), Log::ERR);
        if ($resPri) {
            foreach ($g_uif_keys as $key=>$val) {
                if ($resPri[$key]==1 
                    || ($resPri[$key]==2 && $r==1)) {
                    $otherInfoArr[$val] = 0;
                    $resPri[$key] = 0;
                }
            }
            //Log::write('otherInfoArr:'.  json_encode($otherInfoArr), Log::ERR);
            return $resPri;
        }
        return NULL;
    }
    //根据隐私信息返回字符串
    function textFilter($content, $txtFlag=0){
        $txtArr = array('', '用户设置为隐藏', '不可见');
        if ($content===0) {
            return $txtArr[$txtFlag];
        }
        return $content;
    }
    
    //构造所需域名
    function getDomain($sub='www') {
        $host = $_SERVER['HTTP_HOST'];
        $hostr = explode('.', $host);
        $domain = NULL;
        $segc = count($hostr);
        if ($segc==3) {
            $domain = $sub.".".$hostr[$segc-2].".".$hostr[$segc-1];
        }
        //是ip地址的情况
        else if ($segc==4 && ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$",$host)) {
            $domain = $host;
        }
        else {
            $domain = $host;
        }
        return $domain;
    }
    
    //职位结束状态
    function toJobStatus($status) {
        $strs = array('已结算','未结算');
        if (!$strs[$status]) {
            return '暂无';
        }
        return $strs[$status];
    }
    
    //屏蔽邮箱地址
    function convEmail($email) {
        if (strpos($email, '@')>0) {
            return hidemail($email);
        }
        else {
            return $email;
        }
    }
    
    //对用户提交内容屏蔽QQ号或电话
    function qqTelFilter($text) {
        $regex = "/[0-9\x{96F6}\x{4E00}\x{4E8C}\x{4E09}\x{56DB}\x{4E94}\x{516D}\x{4E03}\x{516B}\x{4E5D}]{7,11}/u";
        return preg_replace($regex, "[本部分内容被系统屏蔽]", $text);
    }
    
    //给消息内容添加操作链接
    function logPost($msg, $url, $t, $opname = "查看") {
        return $msg."<td class=\"operation\"><a href=\"javascript:void(0);\" data-url=\"".$url."\">".$opname."</a>&nbsp;|&nbsp;".date("Y-m-d H:i", $t)."</td>";
    }
    //去掉office_log内容里的operation节点
    function trimOperation($html) {
        $pos = strpos($html, "</td>");
        if ($pos>0 && $pos<(strlen($html)-1)) {
            return substr($html, 0, $pos+5);
        }
        return $html;
    }
    
    //组装通知数组
    function pushLog(&$logarray, $uid, $text, $ct=null) {
        $log = array(
            'uid'=>$uid,
            'content'=>$text,
            'ctime'=>$ct?$ct:  time(),
        );
        $logarray[] = $log;
    }
    
    
//查询银行信息
function bankInfo($card, $banklist) 
{ 
  $card_8 = substr($card, 0, 8); 
  if (isset($banklist[$card_8])) { 
    return $banklist[$card_8];
  }
  $card_6 = substr($card, 0, 6); 
  if (isset($banklist[$card_6])) { 
    return $banklist[$card_6];
  } 
  $card_5 = substr($card, 0, 5); 
  if (isset($banklist[$card_5])) { 
    return $banklist[$card_5];
  } 
  $card_4 = substr($card, 0, 4); 
  if (isset($banklist[$card_4])) { 
    return $banklist[$card_4];
  } 
  return '该卡号信息暂未录入'; 
}
?>
